﻿using AntUnion.FrameWork.Model.Models;
using AntUnion.FrameWork.Web.Service;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AntUnion.FrameWork.Web.Areas.Console.Controllers
{
    [Area("Console")]
    public class MtServiceController : BaseController
    {
        private readonly IWebHostEnvironment _hostingEnv;
        private readonly mtContext _context;

        public MtServiceController(mtContext context, IWebHostEnvironment hostingEnv) : base(context, hostingEnv)
        {
            _context = context;
            _hostingEnv = hostingEnv;
        }

        #region 获取列表
        public IActionResult Index()
        {
            return View();
        }
        [HttpGet]
        public async Task<JsonResult> GetListJson(int page, int limit)
        {
            ListResult res = new ListResult();
            try
            {
                var data = from y in _context.Mt5Servers
                           select new
                           {
                               index = y.Id,
                               sort = y.Sort,
                               server = y.MetatraderName,
                               type = y.Type,
                               tradingPlatform = y.Type,
                               serverAddress = y.MetatraderServer,
                               serverPort = y.MetatraderPort,
                               manageAccount = y.MetatraderLogin,
                               accountStartNo = y.StartLogin,
                               accountEndNo = y.EndLogin,
                               state = y.State,
                               isDefault = y.Default
                           };
                res.Count = data.Count();
                if (page == 0 && limit == 0)
                {
                    res.Data = await data.OrderBy(k => k.sort).ToArrayAsync();
                }
                else
                {
                    res.Data = await data.OrderBy(k => k.sort).Skip((page - 1) * limit).Take(limit).ToArrayAsync();
                }
                res.Code = 0;
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }


        }
        #endregion

        #region 新增服务器设置
        public IActionResult AddServerSetting()
        {
            return View();
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> AddServerSetting(Mt5Server model)
        {
            Result res = new Result();
            try
            {
                _context.Add(model);
                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();

                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }

        #endregion

        #region 更新服务器设置
        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="intState"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> UpdateState(int id, int intState)
        {
            Result res = new Result();
            try
            {
                Mt5Server mt5Server = await _context.Mt5Servers.FindAsync(id);
                mt5Server.State = intState;

                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }

        #endregion

        #region 修改设置
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }
            Mt5Server mt5Server = await _context.Mt5Servers.FindAsync(id);
            if (mt5Server == null)
            {
                return NotFound();
            }
            return View(mt5Server);
        }
        [HttpPost]
        public async Task<JsonResult> Edit(Mt5Server item)
        {
            Result res = new Result();
            try
            {

                Mt5Server mt5Server = await _context.Mt5Servers.FindAsync(item.Id);
                if (mt5Server == null)
                {
                    res.Code = 1;
                    res.Msg = "";
                    return new JsonResult(res);
                }
                if (item.MetatraderPassword != null)
                    mt5Server.MetatraderPassword = item.MetatraderPassword;
                mt5Server.State = item.State;
                mt5Server.Sort = item.Sort;
                mt5Server.MetatraderName = item.MetatraderName;
                mt5Server.MetatraderServer = item.MetatraderServer;
                mt5Server.MetatraderPort = item.MetatraderPort;
                mt5Server.MetatraderLogin = item.MetatraderLogin;
                mt5Server.StartLogin = item.StartLogin;
                mt5Server.EndLogin = item.EndLogin;
                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 删除设置
        [HttpPost, ActionName("Delete")]
        public JsonResult Delete(int id)
        {
            Result res = new Result();
            try
            {
                Mt5Server mt5Server = _context.Mt5Servers.Find(id);
                _context.Mt5Servers.Remove(mt5Server);
                res.Code = 0;
                res.Data = _context.SaveChanges();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region MT5分组
        public IActionResult Mt5group()
        {
            return View();
        }
        [HttpGet]
        public async Task<JsonResult> GetMt5groupListJson(int page, int limit)
        {
            ListResult res = new ListResult();
            try
            {
                var data = from y in _context.Mt5Groups
                           select new
                           {
                               index = y.Mt5ServerId,
                               MTgroups = y.Group,
                               accountStartNo = y.StartLogin,
                               accountEndNo = y.EndLogin

                           };
                res.Count = data.Count();
                if (page == 0 && limit == 0)
                {
                    res.Data = await data.OrderBy(k => k.index).ToArrayAsync();
                }
                else
                {
                    res.Data = await data.OrderBy(k => k.index).Skip((page - 1) * limit).Take(limit).ToArrayAsync();
                }
                res.Code = 0;
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }


        }
        #endregion

        #region 测试连接
        public JsonResult TestConnection(Mt5Server item)
        {
            Result res = new Result();
            try
            {
                MT5CommonHelper mT5CommonHelper = new MT5CommonHelper();
                bool MTRetCode = mT5CommonHelper.TestConnect(_context, item.MetatraderServer, item.MetatraderPassword, item.MetatraderLogin, item.MetatraderPort);
                if (MTRetCode)
                    res.Code = 0;
                else
                {
                    res.Code = 1;
                    res.Msg = "connectFailed";
                }

                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 修改是否默认
        [HttpPost]
        public async Task<JsonResult> UpdateisDefault(int id, int isDefault)
        {
            Result res = new Result();
            try
            {
                Mt5Server mt5Server = new Mt5Server();
                if (isDefault == 1)
                {
                    mt5Server = _context.Mt5Servers.Where(k => k.Default == 1).FirstOrDefault();
                    if (mt5Server != null)
                    {
                        res.Code = 1;
                        res.Msg = "cancelCurrent";
                        return new JsonResult(res);
                    }
                }
                mt5Server = await _context.Mt5Servers.FindAsync(id);
                mt5Server.Default = isDefault;

                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

    }
}
